package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ISetmealService;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * TODO
 *
 * @Author mr.Du
 * @Date 2025/6/2 2025/6/2
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private IDishServiceImpl dishService;

    @Autowired
    private ISetmealService setmealService;

    /**
     * 添加购物车
     *
     * @param dto
     */
    @Override
    public void add(ShoppingCartDTO dto) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto, shoppingCart);

        //判断是否添加的是菜品
        if (dto.getDishId() != null) {
            Dish dish = dishService.lambdaQuery().
                    eq(Dish::getId, dto.getDishId())
                    .one();
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setName(dish.getName());
            shoppingCart.setAmount(dish.getPrice());
        } else {
            //否则添加的就是套餐
            Setmeal setmeal = setmealService.lambdaQuery()
                    .eq(Setmeal::getId, dto.getSetmealId())
                    .one();
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setAmount(setmeal.getPrice());
        }
        //基础字段处理
        if (shoppingCart.getNumber() != null && shoppingCart.getNumber() >= 1) {
            shoppingCart.setNumber(shoppingCart.getNumber() + 1);
        }
        shoppingCart.setNumber(1);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        this.save(shoppingCart);
    }

    /**
     * 查看购物车
     */
    @Override
    public List<ShoppingCart> shoppingCartList() {
        List<ShoppingCart> shoppingCartList = this.lambdaQuery()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .list();
        return shoppingCartList;
    }

    /**
     * 清空购物车
     */
    @Override
    public void clean() {
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartMapper.delete(wrapper);
    }
}
